import hashlib
import os
import time


# 1. 上传的图片直接存储到对象存储 调接口保存图像名称和使用状态 保存文章时把状态改为True
# 2. 上传到服务器，服务器上传到对象存储
def write_file_local(file, file_type, catalog=''):
    md5 = hashlib.md5()
    md5.update((file.name + str(time.time())).encode('utf-8'))
    file_name = md5.hexdigest() + '.' + file_type
    file_path = './upload/' + catalog
    check_file_path(file_path)
    try:
        with open(file_path + file_name, 'wb+') as f:
            for chunk in file:
                f.write(chunk)
    except:
        if os.path.exists(file_path + file_name):
            os.remove(file_path + file_name)
        return False
    else:
        return file_name


def check_file_path(path):
    if not os.path.exists(path):
        os.mkdir(path)


def delete_old_file(path):
    if os.path.exists(path):
        os.remove(path)
